// 权限体系配置模块
class PermissionSystemManager {
    // 权限数据存储
    static permissions = [
        { id: 1, name: '用户管理', code: 'user:manage', type: '菜单权限', roles: ['管理员'], description: '允许管理所有用户账号', status: 'active' },
        { id: 2, name: '课程管理', code: 'course:manage', type: '菜单权限', roles: ['管理员', '教师'], description: '允许管理课程内容', status: 'active' },
        { id: 3, name: '成绩查看', code: 'score:view', type: '数据权限', roles: ['管理员', '教师', '学员'], description: '允许查看成绩信息', status: 'active' }
    ];

    // 获取所有权限
    static getAllPermissions() {
        return [...this.permissions];
    }

    // 根据ID获取权限
    static getPermissionById(id) {
        return this.permissions.find(perm => perm.id === id);
    }

    static loadContent(container) {
        container.innerHTML = `
            <div class="description">
                配置系统的权限体系，定义不同角色对系统功能的访问权限。
            </div>

            <div class="actions">
                <button class="btn btn-primary btn-add-permission"><i class="fas fa-plus"></i> 新增权限</button>
                <button class="btn btn-default btn-edit-permission-batch"><i class="fas fa-edit"></i> 修改权限</button>
                <button class="btn btn-danger btn-delete-permission-batch"><i class="fas fa-trash"></i> 删除权限</button>
                <div class="search-area">
                    <input type="text" id="search-permission-input" placeholder="搜索权限名称...">
                    <button id="search-permission-btn" class="btn btn-primary"><i class="fas fa-search"></i> 搜索</button>
                </div>
            </div>
            
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="selectAllPermissions"></th>
                            <th>权限名称</th>
                            <th>权限代码</th>
                            <th>权限类型</th>
                            <th>关联角色</th>
                            <th>描述</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><input type="checkbox" class="rowCheckbox"></td>
                            <td>用户管理</td>
                            <td>user:manage</td>
                            <td>菜单权限</td>
                            <td>管理员</td>
                            <td>允许管理所有用户账号</td>
                            <td><button class="status-btn active">启用</button></td>
                            <td class="operation">
                                <a href="#"><i class="fas fa-edit"></i> 编辑</a>
                                <a href="#"><i class="fas fa-trash"></i> 删除</a>
                            </td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" class="rowCheckbox"></td>
                            <td>课程管理</td>
                            <td>course:manage</td>
                            <td>菜单权限</td>
                            <td>管理员,教师</td>
                            <td>允许管理课程内容</td>
                            <td><button class="status-btn active">启用</button></td>
                            <td class="operation">
                                <a href="#"><i class="fas fa-edit"></i> 编辑</a>
                                <a href="#"><i class="fas fa-trash"></i> 删除</a>
                            </td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" class="rowCheckbox"></td>
                            <td>成绩查看</td>
                            <td>score:view</td>
                            <td>数据权限</td>
                            <td>管理员,教师,学员</td>
                            <td>允许查看成绩信息</td>
                            <td><button class="status-btn active">启用</button></td>
                            <td class="operation">
                                <a href="#"><i class="fas fa-edit"></i> 编辑</a>
                                <a href="#"><i class="fas fa-trash"></i> 删除</a>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <div class="pagination">
                <a href="#">上一页</a>
                <a href="#" class="active">1</a>
                <a href="#">2</a>
                <a href="#">3</a>
                <a href="#">4</a>
                <a href="#">5</a>
                <a href="#">下一页</a>
            </div>
        `;
        
        // 设置全选功能
        mainManager.setupSelectAll('selectAllPermissions', 'rowCheckbox');

        // 设置操作按钮事件
        systemManager.setupActionButtons(container);

        // 新增权限按钮
        const addPermissionBtn = container.querySelector('.btn-add-permission');
        if (addPermissionBtn) {
            addPermissionBtn.addEventListener('click', () => {
                AddPermissionModal.showModal();
            });
        }

        // 编辑和删除权限按钮（事件委托）
        const tableBody = container.querySelector('.table-container tbody');
        if (tableBody) {
            tableBody.addEventListener('click', (e) => {
                const editButton = e.target.closest('.operation a:first-child');
                if (editButton) {
                    e.preventDefault();
                    const row = editButton.closest('tr');
                    if (row) {
                        const permissionData = {
                            id: row.rowIndex,
                            name: row.cells[1].textContent,
                            code: row.cells[2].textContent,
                            type: row.cells[3].textContent,
                            roles: row.cells[4].textContent,
                            description: row.cells[5].textContent,
                            status: row.cells[6].querySelector('.status-btn').classList.contains('active') ? 'active' : 'inactive'
                        };
                        EditPermissionModal.showModal(permissionData);
                    }
                }

                const deleteButton = e.target.closest('.operation a:nth-child(2)');
                if (deleteButton) {
                    e.preventDefault();
                    const row = deleteButton.closest('tr');
                    if (row) {
                        const permissionName = row.cells[1].textContent;
                        PermissionSystemManager.showDeleteConfirm(permissionName, () => {
                            const permissionId = row.rowIndex;
                            const index = PermissionSystemManager.permissions.findIndex(p => p.id === permissionId);
                            if (index !== -1) {
                                PermissionSystemManager.permissions.splice(index, 1);
                                alert('删除权限成功');
                                PermissionSystemManager.loadContent(container);
                            }
                        });
                    }
                }
            });
        }

        // 设置搜索功能
        const searchButton = container.querySelector('.search-area button');
        if (searchButton) {
            searchButton.addEventListener('click', () => {
                systemManager.search('permission-system');
            });
        }
    }

    // 显示删除确认弹窗
    static showDeleteConfirm(permissionName, onConfirm) {
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content" style="max-width: 400px;">
                <div class="modal-header">
                    <h3>删除确认</h3>
                    <button class="modal-close-btn"><i class="fas fa-times"></i></button>
                </div>
                <div style="padding: 20px; font-size: 16px; color: #333;">
                    确定要删除权限"${permissionName}"吗？
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" id="delete-cancel-btn">取消</button>
                    <button type="button" class="btn btn-danger" id="delete-confirm-btn">确认删除</button>
                </div>
            </div>
        `;
        document.body.appendChild(modal);

        const closeBtn = modal.querySelector('.modal-close-btn');
        const cancelBtn = modal.querySelector('#delete-cancel-btn');
        const confirmBtn = modal.querySelector('#delete-confirm-btn');
        const overlay = modal.querySelector('.modal-overlay');

        const closeModal = () => {
            modal.classList.remove('show');
            setTimeout(() => modal.remove(), 300);
        };

        closeBtn.addEventListener('click', closeModal);
        cancelBtn.addEventListener('click', closeModal);
        overlay.addEventListener('click', closeModal);
        confirmBtn.addEventListener('click', () => {
            onConfirm();
            closeModal();
        });

        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') closeModal();
        });

        setTimeout(() => modal.classList.add('show'), 10);
    }
}

// 新增权限模态框
class AddPermissionModal {
    static showModal() {
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.id = 'addPermissionModal';
        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h3>新增权限</h3>
                    <button class="modal-close-btn"><i class="fas fa-times"></i></button>
                </div>
                <form class="add-permission-form">
                    <div class="form-group">
                        <label for="permission-name">权限名称 <span class="required">*</span></label>
                        <input type="text" id="permission-name" name="name" class="form-control" required>
                        <div class="error-text" id="permission-name-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="permission-code">权限代码 <span class="required">*</span></label>
                        <input type="text" id="permission-code" name="code" class="form-control" placeholder="例如: user:manage" required>
                        <div class="error-text" id="permission-code-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="permission-type">权限类型 <span class="required">*</span></label>
                        <select id="permission-type" name="type" class="form-control" required>
                            <option value="">请选择</option>
                            <option value="菜单权限">菜单权限</option>
                            <option value="数据权限">数据权限</option>
                            <option value="操作权限">操作权限</option>
                        </select>
                        <div class="error-text" id="permission-type-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="permission-roles">关联角色 <span class="required">*</span></label>
                        <input type="text" id="permission-roles" name="roles" class="form-control" placeholder="多个角色用逗号分隔" required>
                        <div class="error-text" id="permission-roles-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="permission-description">描述</label>
                        <textarea id="permission-description" name="description" class="form-control" rows="3"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="permission-status">状态 <span class="required">*</span></label>
                        <select id="permission-status" name="status" class="form-control" required>
                            <option value="active">启用</option>
                            <option value="inactive">禁用</option>
                        </select>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" id="cancel-btn">取消</button>
                        <button type="submit" class="btn btn-primary" id="save-btn" disabled>保存</button>
                    </div>
                </form>
            </div>
        `;
        document.body.appendChild(modal);
        this.initEvents(modal);
        setTimeout(() => modal.classList.add('show'), 10);
    }

    static initEvents(modal) {
        const form = modal.querySelector('.add-permission-form');
        const closeBtn = modal.querySelector('.modal-close-btn');
        const cancelBtn = modal.querySelector('#cancel-btn');
        const overlay = modal.querySelector('.modal-overlay');

        closeBtn.addEventListener('click', () => this.closeModal(modal));
        cancelBtn.addEventListener('click', () => this.closeModal(modal));
        overlay.addEventListener('click', () => this.closeModal(modal));
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') this.closeModal(modal);
        });

        this.initFormValidation(form);
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            this.submitForm(form);
        });
    }

    static initFormValidation(form) {
        const fields = ['name', 'code', 'type', 'roles'];
        fields.forEach(field => {
            const input = form[field];
            input.addEventListener('input', () => {
                this.validateField(field, input.value);
                this.checkFormValidity(form);
            });
            input.addEventListener('blur', () => {
                this.validateField(field, input.value);
            });
        });
    }

    static validateField(field, value) {
        const errorElement = document.getElementById(`permission-${field}-error`);
        let errorMessage = '';

        if (!value.trim()) {
            errorMessage = '此字段不能为空';
        } else if (field === 'code' && !/^[a-z]+:[a-z]+$/.test(value)) {
            errorMessage = '权限代码格式错误，应为：模块:操作';
        }

        errorElement.textContent = errorMessage;
        return !errorMessage;
    }

    static checkFormValidity(form) {
        const fields = ['name', 'code', 'type', 'roles'];
        const allValid = fields.every(field => {
            const value = form[field].value;
            return this.validateField(field, value);
        });
        form.querySelector('#save-btn').disabled = !allValid;
    }

    static submitForm(form) {
        const saveBtn = form.querySelector('#save-btn');
        saveBtn.textContent = '保存中...';
        saveBtn.disabled = true;

        const formData = {
            name: form.name.value,
            code: form.code.value,
            type: form.type.value,
            roles: form.roles.value.split(',').map(r => r.trim()),
            description: form.description.value,
            status: form.status.value
        };

        setTimeout(() => {
            PermissionSystemManager.permissions.push({
                id: PermissionSystemManager.permissions.length + 1,
                ...formData
            });
            alert('新增权限成功');
            this.closeModal(document.getElementById('addPermissionModal'));
            const contentContainer = document.getElementById('permission-system');
            if (contentContainer) {
                PermissionSystemManager.loadContent(contentContainer);
            }
        }, 1000);
    }

    static closeModal(modal) {
        modal.classList.remove('show');
        setTimeout(() => modal.remove(), 300);
    }
}

// 编辑权限模态框
class EditPermissionModal {
    static showModal(permissionData) {
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.id = 'editPermissionModal';
        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h3>编辑权限</h3>
                    <button class="modal-close-btn"><i class="fas fa-times"></i></button>
                </div>
                <form class="edit-permission-form">
                    <div class="form-group">
                        <label for="edit-permission-name">权限名称 <span class="required">*</span></label>
                        <input type="text" id="edit-permission-name" name="name" class="form-control" value="${permissionData.name}" required>
                        <div class="error-text" id="edit-permission-name-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="edit-permission-code">权限代码 <span class="required">*</span></label>
                        <input type="text" id="edit-permission-code" name="code" class="form-control" value="${permissionData.code}" disabled>
                        <div class="error-text" id="edit-permission-code-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="edit-permission-type">权限类型 <span class="required">*</span></label>
                        <select id="edit-permission-type" name="type" class="form-control" required>
                            <option value="菜单权限" ${permissionData.type === '菜单权限' ? 'selected' : ''}>菜单权限</option>
                            <option value="数据权限" ${permissionData.type === '数据权限' ? 'selected' : ''}>数据权限</option>
                            <option value="操作权限" ${permissionData.type === '操作权限' ? 'selected' : ''}>操作权限</option>
                        </select>
                        <div class="error-text" id="edit-permission-type-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="edit-permission-roles">关联角色 <span class="required">*</span></label>
                        <input type="text" id="edit-permission-roles" name="roles" class="form-control" value="${permissionData.roles}" required>
                        <div class="error-text" id="edit-permission-roles-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="edit-permission-description">描述</label>
                        <textarea id="edit-permission-description" name="description" class="form-control" rows="3">${permissionData.description}</textarea>
                    </div>
                    <div class="form-group">
                        <label for="edit-permission-status">状态 <span class="required">*</span></label>
                        <select id="edit-permission-status" name="status" class="form-control" required>
                            <option value="active" ${permissionData.status === 'active' ? 'selected' : ''}>启用</option>
                            <option value="inactive" ${permissionData.status === 'inactive' ? 'selected' : ''}>禁用</option>
                        </select>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" id="cancel-btn">取消</button>
                        <button type="submit" class="btn btn-primary" id="save-btn">保存</button>
                    </div>
                </form>
            </div>
        `;
        document.body.appendChild(modal);
        this.initEvents(modal, permissionData);
        setTimeout(() => modal.classList.add('show'), 10);
    }

    static initEvents(modal, permissionData) {
        const form = modal.querySelector('.edit-permission-form');
        const closeBtn = modal.querySelector('.modal-close-btn');
        const cancelBtn = modal.querySelector('#cancel-btn');
        const overlay = modal.querySelector('.modal-overlay');

        closeBtn.addEventListener('click', () => this.closeModal(modal));
        cancelBtn.addEventListener('click', () => this.closeModal(modal));
        overlay.addEventListener('click', () => this.closeModal(modal));
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') this.closeModal(modal);
        });

        this.initFormValidation(form);
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            this.submitForm(form, permissionData);
        });
    }

    static initFormValidation(form) {
        const fields = ['name', 'type', 'roles'];
        fields.forEach(field => {
            const input = form[field];
            input.addEventListener('input', () => {
                this.validateField(field, input.value);
                this.checkFormValidity(form);
            });
        });
    }

    static validateField(field, value) {
        const errorElement = document.getElementById(`edit-permission-${field}-error`);
        let errorMessage = '';

        if (!value.trim()) {
            errorMessage = '此字段不能为空';
        }

        errorElement.textContent = errorMessage;
        return !errorMessage;
    }

    static checkFormValidity(form) {
        const fields = ['name', 'type', 'roles'];
        const allValid = fields.every(field => {
            const value = form[field].value;
            return this.validateField(field, value);
        });
        form.querySelector('#save-btn').disabled = !allValid;
    }

    static submitForm(form, permissionData) {
        const saveBtn = form.querySelector('#save-btn');
        saveBtn.textContent = '保存中...';
        saveBtn.disabled = true;

        const formData = {
            name: form.name.value,
            type: form.type.value,
            roles: form.roles.value.split(',').map(r => r.trim()),
            description: form.description.value,
            status: form.status.value
        };

        setTimeout(() => {
            const permission = PermissionSystemManager.permissions.find(p => p.id === permissionData.id);
            if (permission) {
                Object.assign(permission, formData);
            }
            alert('编辑权限成功');
            this.closeModal(document.getElementById('editPermissionModal'));
            const contentContainer = document.getElementById('permission-system');
            if (contentContainer) {
                PermissionSystemManager.loadContent(contentContainer);
            }
        }, 1000);
    }

    static closeModal(modal) {
        modal.classList.remove('show');
        setTimeout(() => modal.remove(), 300);
    }
}